package com.yin.waimai.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yin.waimai.config.AmapConfig;
import com.yin.waimai.service.RegionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings("unchecked")
public class RegionServiceImpl implements RegionService {

    private static final Logger log = LoggerFactory.getLogger(RegionServiceImpl.class);
    private static final String DISTRICT_URL = "https://restapi.amap.com/v3/config/district";
    private static final long CACHE_EXPIRATION = 7; // 缓存过期时间（天）

    private final AmapConfig amapConfig;
    private final ObjectMapper objectMapper;
    private final HttpClient httpClient;
    private final RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public RegionServiceImpl(AmapConfig amapConfig, ObjectMapper objectMapper, RedisTemplate<String, Object> redisTemplate) {
        this.amapConfig = amapConfig;
        this.objectMapper = objectMapper;
        this.redisTemplate = redisTemplate;
        this.httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
                .connectTimeout(Duration.ofSeconds(10))
                .build();
    }

    @Override
    public List<Map<String, String>> getAllProvinces() {
        // 先从Redis缓存获取
        String cacheKey = "region:provinces";
        Object cachedData = redisTemplate.opsForValue().get(cacheKey);
        
        if (cachedData != null) {
            return (List<Map<String, String>>) cachedData;
        }
        
        // 缓存未命中，调用高德API
        List<Map<String, String>> provinces = new ArrayList<>();
        try {
            URI uri = UriComponentsBuilder
                    .fromHttpUrl(DISTRICT_URL)
                    .queryParam("key", amapConfig.getWebServiceKey())
                    .queryParam("keywords", "中国")
                    .queryParam("subdistrict", "1")
                    .queryParam("extensions", "base")
                    .encode(StandardCharsets.UTF_8)
                    .build(false)
                    .toUri();

            HttpRequest httpRequest = HttpRequest.newBuilder().uri(uri)
                    .header("User-Agent", "Mozilla/5.0")
                    .GET().timeout(Duration.ofSeconds(15)).build();
            
            HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            String responseBody = httpResponse.body();
            
            if (httpResponse.statusCode() == 200 && responseBody != null) {
                JsonNode root = objectMapper.readTree(responseBody);
                if ("1".equals(root.path("status").asText())) {
                    JsonNode districts = root.path("districts");
                    if (districts.isArray() && districts.size() > 0) {
                        JsonNode china = districts.get(0);
                        JsonNode provinceNodes = china.path("districts");
                        
                        if (provinceNodes.isArray()) {
                            for (JsonNode province : provinceNodes) {
                                Map<String, String> provinceMap = new HashMap<>();
                                provinceMap.put("name", province.path("name").asText());
                                provinceMap.put("code", province.path("adcode").asText());
                                provinces.add(provinceMap);
                            }
                            
                            // 存入Redis缓存
                            redisTemplate.opsForValue().set(cacheKey, provinces, CACHE_EXPIRATION, TimeUnit.DAYS);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取省份列表失败", e);
        }
        
        return provinces;
    }

    @Override
    public List<Map<String, String>> getCitiesByProvince(String provinceCode) {
        // 先从Redis缓存获取
        String cacheKey = "region:cities:" + provinceCode;
        Object cachedData = redisTemplate.opsForValue().get(cacheKey);
        
        if (cachedData != null) {
            return (List<Map<String, String>>) cachedData;
        }
        
        // 缓存未命中，调用高德API
        List<Map<String, String>> cities = new ArrayList<>();
        try {
            URI uri = UriComponentsBuilder
                    .fromHttpUrl(DISTRICT_URL)
                    .queryParam("key", amapConfig.getWebServiceKey())
                    .queryParam("keywords", provinceCode)
                    .queryParam("subdistrict", "1")
                    .queryParam("extensions", "base")
                    .encode(StandardCharsets.UTF_8)
                    .build(false)
                    .toUri();

            HttpRequest httpRequest = HttpRequest.newBuilder().uri(uri)
                    .header("User-Agent", "Mozilla/5.0")
                    .GET().timeout(Duration.ofSeconds(15)).build();
            
            HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            String responseBody = httpResponse.body();
            
            if (httpResponse.statusCode() == 200 && responseBody != null) {
                JsonNode root = objectMapper.readTree(responseBody);
                if ("1".equals(root.path("status").asText())) {
                    JsonNode districts = root.path("districts");
                    if (districts.isArray() && districts.size() > 0) {
                        JsonNode province = districts.get(0);
                        JsonNode cityNodes = province.path("districts");
                        
                        if (cityNodes.isArray()) {
                            for (JsonNode city : cityNodes) {
                                Map<String, String> cityMap = new HashMap<>();
                                cityMap.put("name", city.path("name").asText());
                                cityMap.put("code", city.path("adcode").asText());
                                cities.add(cityMap);
                            }
                            
                            // 存入Redis缓存
                            redisTemplate.opsForValue().set(cacheKey, cities, CACHE_EXPIRATION, TimeUnit.DAYS);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取城市列表失败", e);
        }
        
        return cities;
    }

    @Override
    public List<Map<String, String>> getDistrictsByCity(String cityCode) {
        // 先从Redis缓存获取
        String cacheKey = "region:districts:" + cityCode;
        Object cachedData = redisTemplate.opsForValue().get(cacheKey);
        
        if (cachedData != null) {
            return (List<Map<String, String>>) cachedData;
        }
        
        // 缓存未命中，调用高德API
        List<Map<String, String>> districts = new ArrayList<>();
        try {
            URI uri = UriComponentsBuilder
                    .fromHttpUrl(DISTRICT_URL)
                    .queryParam("key", amapConfig.getWebServiceKey())
                    .queryParam("keywords", cityCode)
                    .queryParam("subdistrict", "1")
                    .queryParam("extensions", "base")
                    .encode(StandardCharsets.UTF_8)
                    .build(false)
                    .toUri();

            HttpRequest httpRequest = HttpRequest.newBuilder().uri(uri)
                    .header("User-Agent", "Mozilla/5.0")
                    .GET().timeout(Duration.ofSeconds(15)).build();
            
            HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            String responseBody = httpResponse.body();
            
            if (httpResponse.statusCode() == 200 && responseBody != null) {
                JsonNode root = objectMapper.readTree(responseBody);
                if ("1".equals(root.path("status").asText())) {
                    JsonNode districtNodes = root.path("districts");
                    if (districtNodes.isArray() && districtNodes.size() > 0) {
                        JsonNode city = districtNodes.get(0);
                        JsonNode districtList = city.path("districts");
                        
                        if (districtList.isArray()) {
                            for (JsonNode district : districtList) {
                                Map<String, String> districtMap = new HashMap<>();
                                districtMap.put("name", district.path("name").asText());
                                districtMap.put("code", district.path("adcode").asText());
                                districts.add(districtMap);
                            }
                            
                            // 存入Redis缓存
                            redisTemplate.opsForValue().set(cacheKey, districts, CACHE_EXPIRATION, TimeUnit.DAYS);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取区县列表失败", e);
        }
        
        return districts;
    }
}